<?php
namespace think;

CLASS jssdk{

  private $appId;
  private $appSecret;

  public function __construct($appId, $appSecret) {
    $this->appId = $appId;
    $this->appSecret = $appSecret;
  }
  public function getSignPackage() {
    $jsapiTicket = $this->getJsApiTicket();

    // 注意 URL 一定要动态获取，不能 hardcode.
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

    $timestamp = time();
    $nonceStr = $this->createNonceStr();

    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

    $signature = sha1($string);

    $signPackage = array(
      "appId"     => $this->appId,
      "nonceStr"  => $nonceStr,
      "timestamp" => $timestamp,
      "url"       => $url,
      "signature" => $signature,
      "rawString" => $string
    );
    return $signPackage; 
  }

  private function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }

  private function getAccessToken() {


      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
      //2初始化
      $ch = curl_init();
      //3.设置参数
      curl_setopt($ch , CURLOPT_URL, $url);
      curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
      //4.调用接口
      $res = curl_exec($ch);
      //5.关闭curl
      curl_close( $ch );
      $arr = json_decode($res, true);
//    Cookie::set('access_token',$arr['access_token']);
      $access_token = $arr['access_token'];
      Session::set('accessToken',$access_token);
      return $access_token;
  }

  private function getJsApiTicket() {
//      dump(Session::get('accessToken'));
//      die();
        if(Session::get('accessToken') == null){
            $accessToken = $this->getAccessToken();
        }else{
            $accessToken = Session::get('accessToken');
        }
        $urll = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$accessToken."&type=jsapi";
        $access =  file_get_contents($urll);
//      dump($access);
        $result = json_decode($access, true);
//      dump($result);
        $ticket = $result["ticket"];
//      dump($ticket);
        return $ticket;

  }




}

